package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //产生一个4位的随机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("code = "+code);
        //把验证码存放ssesion中
//        session.setAttribute(user.getPhone(), code);优化前存入session
        //优化后存入redis
        redisTemplate.opsForValue().set(user.getPhone(),code,5,TimeUnit.MINUTES);
        return R.success("验证码发送成功");
    }
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto,HttpSession session){
        //判断验证码是否正确
//        String codeS = (String) session.getAttribute(userDto.getPhone());优化前
        //优化后
        String codeS = (String) redisTemplate.opsForValue().get(userDto.getPhone());
        String code = userDto.getCode();
//        String code = "1234";
        if (!code.equals(codeS)){
            return R.error("验证码错误");
        }
        //判断用户是否存在
        //创建条件构造器
        LambdaQueryWrapper<User> userDtoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userDtoLambdaQueryWrapper.eq(User::getPhone,userDto.getPhone());
        User one = userService.getOne(userDtoLambdaQueryWrapper);
        //不存在就注册再放行
        if (one == null){
            //用户不存在，需要注册
            userDto.setName("customer001");
            userDto.setStatus(1);
            userDto.setPhone(userDto.getPhone());
            userService.save(userDto);
        }
        //用户存在，直接存放session返回结果
        session.setAttribute("user",userDto);
        redisTemplate.delete(userDto.getPhone());
        return R.success("登录成功");
    }
}
